<template>
	<view>
		<search-bar
			:mode="2"
			button="outside"
			@search="search"
			@confirm="search"
			:backIcon="true"
			@goBack="back"
			v-model="searchText"
		></search-bar>
		<!-- <nav-bar :fixed="true" color="#ffffff" background-color="#D03032" leftIcon="back" @click-left="back" @click-right="search">
			<view class="search-view">
				<icon-font type="search" size="22" color="#666666" />
				<input
					type="text"
					class="input text-black"
					style="width: 98%;"
					placeholder="搜索商品 领优惠券返现金"
					confirm-type="search"
					@confirm="search"
					v-model="searchText"
				/>
			</view>
			<block slot="right"><text class="text-white margin-right-sm" style="font-size: 14px;" @tap="search">搜索</text></block>
		</nav-bar> -->
		<!-- <type-tabs v-model="shoptabIndex" :fixed="true" :tabs="shopTabs" @change="shoptabchange"></type-tabs> -->
		<!-- <type-tabs v-model="searchtypeIndex" :fixed="true" :tabs="searchtypeTabs" @change="searcTypeChange"></type-tabs> -->
		<view class="navbar">
			<view class="nav-item" v-for="(tab, index) in searchtypeTabs" :key="index" :class="{ current: index === searchtypeIndex }" @click="searcTypeChange(index)">
				<view class="text-df">{{ tab.name }}</view>
				<view class="margin-left-xs" v-if="index == 1">
					<view><icon-font type="arrowup" size="12" :color="searchtypeIndex === 1 && priceOrder === 0 ? '#ec89a6' : '#bfbfbf'"></icon-font></view>
					<view><icon-font type="arrowdown" size="12" :color="searchtypeIndex === 1 && priceOrder === 1 ? '#ec89a6' : '#bfbfbf'"></icon-font></view>
				</view>
				<view class="margin-left-xs" v-if="index == 2">
					<view><icon-font type="arrowup" size="12" :color="searchtypeIndex === 2 && commissionOrder === 0 ? '#ec89a6' : '#bfbfbf'"></icon-font></view>
					<view><icon-font type="arrowdown" size="12" :color="searchtypeIndex === 2 && commissionOrder === 1 ? '#ec89a6' : '#bfbfbf'"></icon-font></view>
				</view>
			</view>
		</view>
		<mescroll-body ref="mescrollRef" :down="downOption" :up="upOption" @up="upCallback"><good-list :list="goods"></good-list></mescroll-body>
		<search-clipboard :searchModal="searchModal" @resetModal="resetSearchModal"></search-clipboard>
	</view>
</template>

<script>
import typeTabs from '@/components/type-tabs.vue';
import goodList from '@/pages/sou/components/good-list.vue';
import searchBar from '@/pages/sou/components/search-bar.vue';

import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js';
var _self; //this容器
export default {
	mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
	components: {
		typeTabs,
		goodList,
		searchBar
	},
	data() {
		return {
			searchText: '', //搜索关键字
			searchType: 'total_sales', //排序类别 total_sales:销量、price:价格、tk_rate:佣金比率
			sortType: '_des', //排序规则 _des:降序、_asc:升序
			shopTabs: [
				{
					name: '淘宝',
					goodList: [
						{ ascGoods: null, descGoods: null, num: 1, y: 0, curPageLen: 0, hasNext: true },
						{ ascGoods: null, descGoods: null, num: 1, y: 0, curPageLen: 0, hasNext: true },
						{ ascGoods: null, descGoods: null, num: 1, y: 0, curPageLen: 0, hasNext: true }
					]
				},
				{
					name: '京东',
					goodList: [
						{ ascGoods: null, descGoods: null, num: 1, y: 0, curPageLen: 0, hasNext: true },
						{ ascGoods: null, descGoods: null, num: 1, y: 0, curPageLen: 0, hasNext: true },
						{ ascGoods: null, descGoods: null, num: 1, y: 0, curPageLen: 0, hasNext: true }
					]
				},
				{
					name: '拼多多',
					goodList: [
						{ ascGoods: null, descGoods: null, num: 1, y: 0, curPageLen: 0, hasNext: true },
						{ ascGoods: null, descGoods: null, num: 1, y: 0, curPageLen: 0, hasNext: true },
						{ ascGoods: null, descGoods: null, num: 1, y: 0, curPageLen: 0, hasNext: true }
					]
				}
			],
			searchtypeTabs: [
				{ name: '综合', type: 'total_sales', sortType: ['_des', '_des'] },
				{ name: '价格', type: 'price', sortType: ['_asc', '_des'] },
				{ name: '佣金', type: 'tk_rate', sortType: ['_asc', '_des'] }
			],

			shoptabIndex: 0, // 当前商家下标
			shoptabpreIndex: 0, // 前一个商家下标
			searchtypeIndex: 0, //当前排序序号
			searchtypepreIndex: 0, //前一个排序序号
			totalPage: 0, //总页数
			downOption: {
				use: false // 不使用下拉刷新
			},
			upOption: {
				noMoreSize: 3, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
				empty: {
					tip: '~ 搜索无结果 ~' // 提示
				}
			},
			priceOrder: 0, //价格排序 0：升序，1：降序
			commissionOrder: 1, //佣金排序 0：升序，1：降序
			searchModal: this.$util.initClipboard()
		};
	},
	computed: {
		goods() {
			// 列表数据
			let tmpasc = this.shopTabs[this.shoptabIndex].goodList[this.searchtypeIndex].ascGoods;
			let tmpdesc = this.shopTabs[this.shoptabIndex].goodList[this.searchtypeIndex].descGoods;
			let flgasc = this._self.sortType == '_asc';
			return flgasc ? tmpasc : tmpdesc;
		}
	},
	onLoad(options) {
		_self = this;
		_self.shoptabIndex = options.type ? options.type : 0;
		if (options.cnt) {
			_self.searchText = JSON.parse(decodeURIComponent(options.cnt));
		}
	},
	onShow() {
		setTimeout(() => {
			_self.$util.searchClipboard(_self.$store.state.searchContent).then(res => {
				_self.searchModal = res;
			});
		}, 200);
	},
	methods: {
		resetSearchModal() {
			_self.searchModal = _self.$util.initClipboard();
		},
		/* 返回按钮事件 */
		back() {
			uni.switchTab({
				url: 'main'
			});
		},

		/* 搜索记录 */
		search() {
			_self.searchtypeIndex = 0;
			_self.searchtypepreIndex = 0;
			_self.searchType = 'total_sales';
			_self.sortType = '_des';
			_self.shopTabs.forEach(item => {
				item.goodList.forEach(gitem => {
					gitem.ascGoods = null;
					gitem.descGoods = null;
					gitem.num = 1;
					gitem.y = 0;
					gitem.curPageLen = 0;
					gitem.hasNext = true;
				});
			});
			_self.$util.setSearchHistory(_self.searchText, _self.$store.state.searchTBStorageHistory);
			_self.mescroll.resetUpScroll();
		},

		/* 商家切换 */
		shoptabchange(index) {
			_self.searchtypeIndex = 0;
			_self.searchtypepreIndex = 0;
			_self.searchType = 'total_sales';
			_self.sortType = '_des';
			// 记录前一个菜单的数据
			let preTab = _self.shopTabs[_self.shoptabpreIndex].goodList[_self.searchtypeIndex];
			preTab.y = _self.mescroll.getScrollTop(); // 滚动条位置
			_self.shoptabpreIndex = index;
			// 当前菜单的数据
			let curTab = _self.shopTabs[index].goodList[_self.searchtypeIndex];
			if (!curTab.ascGoods) {
				// 没有初始化,则初始化
				_self.isChangeTab = true;
				_self.mescroll.resetUpScroll();
			} else {
				// 初始化过,则恢复之前的列表数据
				_self.mescroll.setPageNum(curTab.num + 1); // 恢复当前页码
				_self.mescroll.endSuccess(curTab.curPageLen, curTab.hasNext); // 恢复是否有下一页或显示空布局
				_self.$nextTick(() => {
					_self.mescroll.scrollTo(curTab.y, 0); // 恢复滚动条的位置
				});
			}
		},

		/* 排序类别切换 */
		searcTypeChange(index) {
			let sortTypeIndex = 0;
			if (index > 0) {
				sortTypeIndex = index == 1 ? _self.priceOrder : _self.commissionOrder;
				if (_self.searchtypeIndex == index) {
					if (index == 1) {
						sortTypeIndex = _self.priceOrder = _self.priceOrder == 0 ? 1 : 0;
					} else {
						sortTypeIndex = _self.commissionOrder = _self.commissionOrder == 0 ? 1 : 0;
					}
				}
			}
			_self.searchtypeIndex = index;
			_self.searchType = _self.searchtypeTabs[index].type;
			_self.sortType = _self.searchtypeTabs[index].sortType[sortTypeIndex];
			let flgasc = _self.sortType == '_asc';
			// 记录前一个菜单的数据
			let preTab = _self.shopTabs[_self.shoptabIndex].goodList[_self.searchtypepreIndex];
			preTab.y = 0; //_self.mescroll.getScrollTop(); // 滚动条位置
			_self.searchtypepreIndex = index;
			// 当前菜单的数据
			let curTab = _self.shopTabs[_self.shoptabIndex].goodList[index];
			let tmpgoods = flgasc ? curTab.ascGoods : curTab.descGoods;
			if (!tmpgoods) {
				// 没有初始化,则初始化
				_self.isChangeTab = true;
				_self.mescroll.resetUpScroll();
			} else {
				// 初始化过,则恢复之前的列表数据
				_self.mescroll.setPageNum(curTab.num + 1); // 恢复当前页码
				_self.mescroll.endSuccess(curTab.curPageLen, curTab.hasNext); // 恢复是否有下一页或显示空布局
				_self.$nextTick(() => {
					_self.mescroll.scrollTo(curTab.y, 0); // 恢复滚动条的位置
				});
			}
		},

		/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
		upCallback(page) {
			//联网加载数据
			if (_self.isChangeTab) {
				_self.mescroll.showUpScroll();
			}
			_self
				.getListDataFromNet(page.num, page.size)
				.then(
					curPageData => {
						let flgasc = this._self.sortType == '_asc';
						let curTab = _self.shopTabs[_self.shoptabIndex].goodList[_self.searchtypeIndex];
						if (flgasc) {
							if (page.num == 1) curTab.ascGoods = []; //如果是第一页需手动制空列表
							curTab.ascGoods = curTab.ascGoods.concat(curPageData); //追加新数据
						} else {
							if (page.num == 1) curTab.descGoods = []; //如果是第一页需手动制空列表
							curTab.descGoods = curTab.descGoods.concat(curPageData); //追加新数据
						}
						_self.$nextTick(() => {
							_self.mescroll.endByPage(curPageData.length, _self.totalPage);
							curTab.num = page.num; // 页码
							curTab.curPageLen = curPageData.length; // 当前页长
							curTab.hasNext = _self.mescroll.optUp.hasNext; // 是否还有下一页
							if (_self.isChangeTab) {
								_self.isChangeTab = false;
								_self.mescroll.hideUpScroll();
							}
						});
					},
					error => {
						_self.mescroll.endByPage(0, 0);
						_self.mescroll.hideUpScroll();
					}
				)
				.catch(() => {
					//联网失败, 结束加载
					_self.mescroll.endErr();
				});
		},

		/* 获取查询数据 */
		getListDataFromNet(pageNum, pageSize, successCallback, errorCallback) {
			try {
				const param = {
					currentPage: pageNum,
					pageSize: pageSize,
					condition: {
						keyword: _self.searchText,
						sortType: _self.searchType,
						sort: _self.sortType
					}
				};
				let promise = new Promise(function(resolve, reject) {
					_self.$http.httpRequest('taobao/product/search', param, false).then(res => {
						if (res._tranStatus) {
							_self.totalPage = res._data.totalPage;
							resolve(res._data.pageItems);
						} else {
							let error = {};
							reject('error');
						}
					});
				});
				return promise;
			} catch (e) {
				return Promise.reject(e);
			}
		}
	}
};
</script>

<style lang="scss">
/* 横幅广告 */
.ad-banner {
	width: 100%;
	height: 210rpx;
	background: #fff;
	image {
		width: 100%;
		height: 100%;
	}
}
.search-view {
	width: 98%;
	display: flex;
	background-color: #e7e7e7;
	height: 30px;
	border-radius: 15px;
	padding: 0 4%;
	flex-wrap: nowrap;
	align-items: center;
	margin: 7px 0;
	line-height: 30px;
	background: #f5f5f5;
}

.navbar {
	position: fixed;
	left: 0;
	top: var(--window-top) px;
	display: flex;
	width: 100%;
	height: 50px;
	background: #fff;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.06);
	z-index: 999;
	.nav-item {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 48px;
		font-size: 24rpx;
		color: #555;
		position: relative;
		&.current {
			color: #ec89a6;
			&:after {
				content: '';
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				width: 120rpx;
				height: 0;
				border-bottom: 4rpx solid $base-color;
			}
		}
	}
}
</style>
